/**
 * 模型展示
 * @author gukeming@ds.cn
 */
;
(function () {

    var camera, scene, renderer;
    var renderEnabled, timeOut;
    var controls;
    //创建场景
    function initScene() {
        scene = new THREE.Scene();
    }

    //创建相机
    function initCamera() {
        // //相机设置
        var width = window.innerWidth;
        var height = window.innerHeight;
        var k = width / height;

        var s = 150;
        camera = new THREE.OrthographicCamera(-s * k, s * k, s, -s, 1, 1000);
        camera.position.set(200, 100, 200);
        camera.lookAt(scene.position);
    }

    //创建渲染器
    function initRender() {
        renderer = new THREE.WebGLRenderer();
        renderer.setPixelRatio(window.devicePixelRatio);
        renderer.setSize(window.innerWidth, window.innerHeight);
        renderer.setClearColor(0xffffff, 1);
        document.body.appendChild(renderer.domElement);
    }

    //创建灯光
    function initLight() {
        var ambientLight = new THREE.AmbientLight(0xcccccc, 0.4);
        scene.add(ambientLight);

        var pointLight = new THREE.PointLight(0xffffff, 0.8);
        camera.add(pointLight);
        scene.add(camera);
    }

    //浏览器改变
    function onWindowResize() {
        var s = 150;
        // 重置渲染器输出画布canvas尺寸
        renderer.setSize(window.innerWidth, window.innerHeight);
        // 重置相机投影的相关参数
        k = window.innerWidth / window.innerHeight; //窗口宽高比
        camera.left = -s * k;
        camera.right = s * k;
        camera.top = s;
        camera.bottom = -s;
        // 渲染器执行render方法的时候会读取相机对象的投影矩阵属性projectionMatrix
        // 但是不会每渲染一帧，就通过相机的属性计算投影矩阵(节约计算资源)
        // 如果相机的一些属性发生了变化，需要执行updateProjectionMatrix ()方法更新相机的投影矩阵
        camera.updateProjectionMatrix();
    }

    //加载gltf模型
    function loadGltfModel(modelUrl) {
        var onProgress = function (xhr) {
            if (xhr.lengthComputable) {
                var percentComplete = xhr.loaded / xhr.total * 100;
                console.log(Math.round(percentComplete, 2) + '% downloaded');
            }
        };

        var onError = function () {};

        var loader = new THREE.GLTFLoader()
        loader.load(modelUrl, function (gltf) {

            gltf.scene.traverse(function (child) {

                if (child.isMesh) {

                }
            });
            
            scene.add(gltf.scene);
        }, onProgress, onError);
    }

    //加载obj模型
    function loadObjModel(modelUrl) {
        var onProgress = function (xhr) {
            if (xhr.lengthComputable) {
                var percentComplete = xhr.loaded / xhr.total * 100;
                console.log(Math.round(percentComplete, 2) + '% downloaded');
            }
        };

        var onError = function () {};

        var manager = new THREE.LoadingManager();
        manager.addHandler(/\.dds$/i, new THREE.DDSLoader());
    
        var loader = new THREE.MTLLoader(manager)
        var mtl = modelUrl.replace('.obj', '.mtl');
        loader.load(mtl, function (materials) {
            materials.preload();
            new THREE.OBJLoader(manager)
                .setMaterials(materials)
                .load(modelUrl, function (object) {
                    //object.scale.set(10,10,10)
                    scene.add(object);
                }, onProgress, onError);
        });
    }

    //监听鼠标、键盘事件
    function initControls() {
        controls = new THREE.OrbitControls(camera, renderer.domElement);
        controls.addEventListener('change', function() {
            timeRender();
        }); 
        // 使动画循环使用时阻尼或自转 意思是否有惯性 
        controls.enableDamping = false; 
        //是否可以缩放 
        controls.enableZoom = true; 
        //放大缩小倍数控制
        controls.minZoom = 1;
	    controls.maxZoom = 20;
        //是否自动旋转 
        controls.autoRotate = true; 
        //设置相机距离原点的最远距离 
        controls.minDistance = 200; 
        //设置相机距离原点的最远距离 
        controls.maxDistance = 600; 
        //是否开启右键拖拽 
        controls.enablePan = false;
        
        //上下旋转角度限制
        controls.minPolarAngle = -Math.PI/2; 
        controls.maxPolarAngle = Math.PI/2; 
    }

    //调用一次可以渲染三秒
    function timeRender() {
        //设置为可渲染状态
        renderEnabled = true;
        //清除上次的延迟器
        if (timeOut) {
            clearTimeout(timeOut);
        }
    
        timeOut = setTimeout(function () {
            renderEnabled = false;
        }, 3000);
    }

    function initOther() {
        renderEnabled = true;
        //每次材质和纹理更新，触发重新渲染
        THREE.DefaultLoadingManager.onLoad = function () {
            timeRender();
        };
 
        //窗口改变处理
        window.onresize = onWindowResize
    }

    //循环渲染
    function render() {
        //执行渲染操作
        if(renderEnabled) {
            renderer.render(scene, camera);
        }
        
        //请求再次执行渲染函数render
        requestAnimationFrame(render);

        if (controls) {
            controls.update();
        }
    }


    function cteateModel(modelData) {
        if (!modelData) {
            console.log('modelData 不存在');
            return;
        }

        if (!modelData.modelUrl) {
            console.log('modelUrl 不存在');
            return;
        }
        var modelUrl = modelData.modelUrl || '';

        if (modelUrl.indexOf('obj') > 0) {
            loadObjModel(modelUrl)
        } else if (modelUrl.indexOf('gltf') > 0) {
            loadGltfModel(modelUrl)
        } else {
            console.log('该模型不支持' + modelData.modelUrl);
        }
    }

    function main() {
        initScene();
        initCamera();
        initLight();
        initRender();
        initControls();
        initOther();
        render();
    }

    var t3d = {
        createModel: function (modelData) {
            cteateModel(modelData);
        }
    }
    window.T3D = t3d;
    main();
})()